<?php
if (!defined("_INDEX")) { header("Location: /"); die; }

$answer_id = UV::readInt(strip_tags($route->POST("answer")));
if ($poll_id = $db->getCell("select `poll_id` from `answers` where `answer_id` = '$answer_id' limit 1"))
{
	$user_id = $user->getUserId();
	$user_ip = $_SERVER['REMOTE_ADDR'];
	$time = time();
	
	// проверка на голос текущего вопроса
	$query = $user->isUser() ?	"select `poll_id` from `user_answers` where (`user_id` = '$user_id' or `user_ip` = '$user_ip') and `poll_id` = '$poll_id' limit 1" :
								"select `poll_id` from `user_answers` where `user_ip` = '$user_ip' and `poll_id` = '$poll_id' limit 1";
	$ua = $db->getCell($query);
	if ($ua)
		die("user");
	
	if ($db->sendQuery("insert into `user_answers` values (NULL,'$poll_id','$answer_id','$user_id','$user_ip','$time')")){
		$answers = $db->getTable("select * from `answers` where `poll_id` = '$poll_id' order by `answer_id`");
		$user_answers_count = $db->getCell("select count(`ua_id`) from `user_answers` where `poll_id` = '$poll_id'");
		$response = "[";
		$count_answers = count($answers);
		foreach ($answers as $key=>$answer){
			$user_answers = $db->getCell("select count(`ua_id`) from `user_answers` where `answer_id` = '".$answer['answer_id']."'");
			$user_answers_percent = round($user_answers/$user_answers_count*100,1);
			$response .= '{"text":"'.$answer['text'].'","percent":"'.$user_answers_percent.'"},';
		}
		echo $response .= '{"all_users":"'.$user_answers_count.'"}]';
	}
	else
		echo "ua";
}
else
	echo "poll";

?>